import React, {useState, useReducer} from "react";
import {Button, Card} from 'antd';

function BasicComponents() {
    const [count, setCount] = useState(0)
    const handelClick = (op) => {
        setCount(pre => op === 'add' ? pre + 1 : pre - 1)
    }
    return (
        <div className={'flex-y-gap'}>
            <h3>当前值为:{count}</h3>
            <div className={'flex-gap'}>
                <Button onClick={() => handelClick('add')}>点击加1</Button>
                <Button onClick={() => handelClick('subtract')}>点击减1</Button>
            </div>

        </div>
    )
}


// state 代表之前的,原来的值
// action = {type:具体操作名称,加还是减;payload:操作附带具体的值,加1或者加N}


function ReducerComponents() {
    /**
     * 1.定义 reducer 函数 把操作状态的代码进行整理
     * 2.import {useReducer} from "react"; 引入 useReducer
     * 3. 创建useReducer  const [count,dispatchCount]  = useReducer(reducer,100)   创建一个Reducer, 传入reducer,返回 count初始值为100 dispatchCount 是操作的方法
     * 4. 使用 dispatchCount  调用 创建useReducer   dispatchCount({type, payload: 1}) 注: reducer函数的state不需要传参  useReducer 会自动存储
     * **/

    /**
     * 写法1:
     * */
    // const reducer = (state, action) => {
    //     switch (action.type) {
    //         case 'add':
    //             return state + action.payload
    //         case 'subtract':
    //             return state - action.payload
    //         default:
    //             return state
    //     }
    // }
    // const [count, dispatchCount] = useReducer(reducer, 100)

    /**
     * 写法2:
     * */

    const useCount = () => {
        const reducer = (state, action) => {
            switch (action.type) {
                case 'add':
                    return state + action.payload
                case 'subtract':
                    return state - action.payload
                default:
                    return state
            }
        }
        return useReducer(reducer, 100)
    }
    const [count, dispatchCount] = useCount()

    const handelClick = (type) => {
        // 调用 dispatchCount
        dispatchCount({type, payload: 1})
    }

    return (
        <div className={'flex-y-gap'}>
            <h3>当前值为:{count}</h3>
            <div className={'flex-gap'}>
                <Button onClick={() => handelClick('add')}>点击加1</Button>
                <Button onClick={() => handelClick('subtract')}>点击减1</Button>
            </div>

        </div>
    )
}

export default () => {
    return (
        <Card hoverable>
            <div>
                <h1>useReducer 的使用:</h1>
                <div className={'definition'}>useReducer是React
                    Hooks的一部分，它用来替代useState。它接收一个reducer函数和一个可选的初始状态值，并返回当前状态以及用于更新状态的dispatch函数。
                </div>

                <div>普通写法:</div>
                <BasicComponents/>
                <div style={{marginTop: 10}}>
                    <div>useReducer写法:</div>
                    <ReducerComponents/>
                </div>

            </div>
        </Card>

    )

}